package com.example.myapplication.database

import androidx.lifecycle.LiveData
import androidx.room.*

/**
 * 持仓记录数据访问对象
 */
@Dao
interface PositionDao {
    
    /**
     * 插入一条持仓记录
     */
    @Insert
    suspend fun insert(position: UserPosition): Long
    
    /**
     * 更新持仓记录
     */
    @Update
    suspend fun update(position: UserPosition)
    
    /**
     * 删除持仓记录
     */
    @Delete
    suspend fun delete(position: UserPosition)
    
    /**
     * 获取所有持仓记录（按时间倒序）
     */
    @Query("SELECT * FROM user_positions ORDER BY timestamp DESC")
    fun getAllPositions(): LiveData<List<UserPosition>>
    
    /**
     * 获取指定股票的所有持仓记录
     */
    @Query("SELECT * FROM user_positions WHERE symbol = :symbol ORDER BY timestamp DESC")
    fun getPositionsBySymbol(symbol: String): LiveData<List<UserPosition>>
    
    /**
     * 获取指定股票的所有未平仓的买入记录
     */
    @Query("SELECT * FROM user_positions WHERE symbol = :symbol AND type = 'BUY' AND isOpen = 1 ORDER BY timestamp ASC")
    suspend fun getOpenBuyPositions(symbol: String): List<UserPosition>
    
    /**
     * 获取指定股票的最新一条未平仓的买入记录
     */
    @Query("SELECT * FROM user_positions WHERE symbol = :symbol AND type = 'BUY' AND isOpen = 1 ORDER BY timestamp ASC LIMIT 1")
    suspend fun getLatestOpenBuyPosition(symbol: String): UserPosition?
    
    /**
     * 获取所有未平仓的买入记录
     */
    @Query("SELECT * FROM user_positions WHERE type = 'BUY' AND isOpen = 1 ORDER BY timestamp DESC")
    fun getAllOpenPositions(): LiveData<List<UserPosition>>
    
    /**
     * 根据ID查询持仓记录
     */
    @Query("SELECT * FROM user_positions WHERE id = :id")
    suspend fun getPositionById(id: Long): UserPosition?
    
    /**
     * 清空所有持仓记录
     */
    @Query("DELETE FROM user_positions")
    suspend fun deleteAll()
    
    /**
     * 统计某只股票的未平仓买入数量
     */
    @Query("SELECT COUNT(*) FROM user_positions WHERE symbol = :symbol AND type = 'BUY' AND isOpen = 1")
    suspend fun getOpenBuyCount(symbol: String): Int
    
    /**
     * 计算某只股票的平均买入价格
     */
    @Query("SELECT AVG(price) FROM user_positions WHERE symbol = :symbol AND type = 'BUY' AND isOpen = 1")
    suspend fun getAverageBuyPrice(symbol: String): Double?
}

